<template>
  <div class="main">
    <!-- 画布背景 -->
    <canvas id="particle-canvas" height="902" width="1245"></canvas>
    <div class="content">
      <div class="login">
        <div class="title">Bing Hotel</div>
        <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            class="demo-ruleForm"
            label-width="55px"
            size="mini"
            status-icon
        >
          <el-form-item label="用户名" prop="loginId">
            <el-input
                v-model="ruleForm.loginId"
                autocomplete="on"
                type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="loginPwd">
            <el-input
                v-model="ruleForm.loginPwd"
                autocomplete="on"
                type="password"
                @keyup.native.enter="loginEnter"
            ></el-input>
          </el-form-item>
          <el-form-item :style="{display: this.type === 0? 'block': 'none'}" label="验证码" prop="code">
            <el-col :span="11">
              <el-input
                  v-model="ruleForm.code"
                  autocomplete="on"
                  type="text"
              ></el-input>
            </el-col>
            <el-col :offset="2" :span="3">
              <el-button circle icon="el-icon-refresh-right" type="info" @click="refreshCode()"></el-button>
            </el-col>
            <el-col :span="8">
              <IdentifyCode :content-height="30" :content-width="100" :identify-code="identifyCode"/>
            </el-col>
          </el-form-item>
          <el-form-item :style="{display: this.type === 0? 'block': 'none'}" >
            <el-checkbox v-model="ruleForm.checkMe">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
            >{{ this.type === 0 ? "登录" : "注册" }}
            </el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            <el-button type="primary" @click="toggle()">{{ this.type === 0 ? "注册" : "登录" }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
// 导入md5加密方法
import { strToMd5 } from "@/util/md5";
import IdentifyCode from "vue-identifycode";

// 导入背景画布方法
import { start } from "@/assets/js/login";

import "nprogress/nprogress.css";

import UUID from "./../util/Common"
import { saveCode } from "@/api/login_api";

export default {
  // DOM加载完成
  mounted() {
    start();
    this.identifyCode = this.createCode();
  },
  components: { IdentifyCode },
  data() {
    // 验证账号
    var validateloginId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    // 验证密码
    var validateloginPwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      // 表单数据
      ruleForm: {
        // 登录名
        loginId: "",
        // 登录密码
        loginPwd: "",
        code: "",
        checkMe: false,
        codeToken: ""
      },
      identifyCode: "",
      type: 0, // 0登录 1注册
      // 表单验证数据
      rules: {
        // 验证账号
        loginId: [{ validator: validateloginId, trigger: "blur" }],
        // 验证密码
        loginPwd: [{ validator: validateloginPwd, trigger: "blur" }],
      },
    };
  },
  methods: {
    // 密码文本框失去焦点回车事件
    loginEnter() {
      this.submitForm("ruleForm");
    },
    // 表单提交方法
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        // 判断表单数据是否验证成功
        if (valid) {
          // 实现登录
          // 对密码进行加密
          this.ruleForm.loginPwd = strToMd5(this.ruleForm.loginPwd);
          let url;
          if (this.type === 0) {
            url = "/user/login";
          } else {
            url = "/user/registry"
          }
          // *************后台验证**************

          let { message, success, token } = await this.$get(
              url,
              this.ruleForm
          );

          // 判断是否登录成功
          if (success) {
            if (this.type === 1) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              this.$router.push("/login");
              return;
            }
            // 服务器会返回一个token,这个token保存的是身份信息,需要保存在浏览器的缓存空间
            window.sessionStorage.setItem("token", token);
            // 在浏览器中保存登录名
            window.localStorage.setItem("loginId", this.ruleForm.loginId);
            // 判断是否记住我
            if (this.ruleForm.checkMe) {
              // 保存密码
              window.localStorage.setItem("loginPwd", this.ruleForm.loginPwd);
            }
            // 将token信息保存到请求头中
            this.$setToken();
            this.$message({
              showClose: true,
              message: message,
              type: "success",
              duration: 1500,
            });
            // 跳转到后台管理界面
            this.$router.push("/layout");
          } else {
            this.$message({
              showClose: true,
              message: message,
              type: "error",
              duration: 1500,
            });
          }

          // *************后台验证**************
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 表单重置方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    createCode() {
      let code = "";
      const codeLength = 4; // 验证码的长度
      // eslint-disable-next-line no-array-constructor
      const random = [2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F", "G",
        "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; // 随机数
      for (let i = 0; i < codeLength; i++) {
        // 循环操作
        const index = Math.floor(Math.random() * 32); // 取得随机数的索引（0~35）
        code += random[index]; // 根据索引取得随机数加到code上
      }
      // 发送验证码请求至服务器
      if (!this.ruleForm.codeToken) {
        this.ruleForm.codeToken = UUID();
      }
      let success = saveCode(this.ruleForm.codeToken, code)
      if (!success) {
        this.$message({
          showClose: true,
          message: "验证码请求异常",
          type: "error",
          duration: 1500,
        });
      }
      return code;
    },
    refreshCode() {
      this.identifyCode = this.createCode();
    },
    toggle() {
      this.type = this.type === 0 ? 1 : 0;
    }
  },
};
</script>
<style lang='scss' scoped>
// 背景画布样式
#particle-canvas {
  width: 100%;
  height: 100vh;
  background: linear-gradient(
          to bottom,
          rgb(10, 10, 50) 0%,
          rgb(60, 10, 60) 100%
  );
  vertical-align: middle;
}

.main {
  width: 100vw;
  height: 100vh;
  position: relative;

  .content {
    position: absolute;
    top: 200px;
    left: 0;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-content: center;
  }

  .login {
    width: 420px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 25px;

    .title {
      font-family: myfont;
      font-size: 30px;
      font-weight: 550;
      color: white;
      text-align: center;
      margin-bottom: 20px;
    }
  }
}

.el-form-item .el-form-item__label {
  margin-bottom: 5px;
  color: rgb(255, 154, 154) !important;
}
</style>
